package com.cali.libcore.http.interceptor

import android.util.Log
import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.*
import java.io.IOException

class DownloadResponseBody(
    private val responseBody: ResponseBody,
    private val action: (Long) -> Unit
) : ResponseBody() {

    private var bufferedSource: BufferedSource? = null

    override fun contentType(): MediaType? = responseBody.contentType()
    override fun contentLength(): Long = responseBody.contentLength()
    override fun source(): BufferedSource? {
        Log.i("donwloading","source")
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(source(responseBody.source()))
        }
        return bufferedSource
    }


    private fun source(source: Source): Source = object : ForwardingSource(source) {
        var totalBytesRead = 0L
        var progress = 0
        val len = contentLength()
        @Throws(IOException::class)
        override fun read(sink: Buffer, byteCount: Long): Long {
            val bytesRead = super.read(sink, byteCount)
            totalBytesRead += if (bytesRead != -1L) bytesRead else 0
            if (bytesRead != -1L) {
                action(totalBytesRead)
            }
            return bytesRead
        }
    }

}